//
//  UserAccount.swift
//  DSWeibo
//
//  Created by J on 16/4/16.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import SVProgressHUD
class UserAccount: NSObject,NSCoding {

     /// token
    var access_token: String?
    var expires_in: NSNumber?{
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow: (expires_in?.doubleValue)!)
        }
        
    }
     /// 授权用户的UID
    var uid: String?
    
    var expires_Date: NSDate?
    
        /// 用户昵称
    var screen_name: NSString?
    /// 用户昵称

    var avatar_large: NSString?
    
    
    
    override init() {
        
    }

    init(dic:[String:AnyObject]) {
      super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("\(key):\(value!)")
    }
    
    
    override var description: String{//重写description
        //定义属性数组
        let properties = ["access_token","expires_in","uid","expires_Date","avatar_large","screen_name"]
        // 根据属性数组 将属性转换为字典
        let dic = self.dictionaryWithValuesForKeys(properties)
        //将字典转换为字符串
        return "\(dic)"
    }

    
    ///获取用户信息
    func loadUserInfo(finished:(account:UserAccount?, error:NSError?)->()){
        assert(access_token != nil,"没有授权")//断言
        
        let path = "2/users/show.json"
        let params = ["access_token":access_token!,"uid":uid!]
        NetWorkTools.shareNetWorkTools().GET(path, parameters: params, success: { (tast:NSURLSessionDataTask, result:AnyObject?) in
            print(result)
            
            //1.判断字典是否有值
            if let dict = result as? [String:AnyObject] {
        
                self.avatar_large = dict["avatar_large"] as? String
                self.screen_name =  dict["screen_name"]! as? String
//                self.saveArchiver()//归档用户信息
                finished(account:self,error:nil)//回调传入的闭包
                return
            }
            
            finished(account:self,error:nil)

            SVProgressHUD.showInfoWithStatus("网络不给力..", mastType: SVProgressHUDMaskType.Black)
        }) { (task:NSURLSessionDataTask?, error:NSError) in
            SVProgressHUD.showInfoWithStatus("网络不给力..", mastType: SVProgressHUDMaskType.Black)
            finished(account:self,error:nil)
        }
        
    }

    
    
    //类方法中直接使用  filepath 对象方法中使用 UserAccount.finalize()
    static let filepath = "account.plist".cache()
    
    //MARK:- 保存和读取
        func saveArchiver(){
            NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filepath)
     }
    
    
    ///解归档
    static var account: UserAccount?
    class func loadAcount() -> UserAccount?{
        //1.判断是否已经加载过
        if account != nil{
            return account
        }
        
   
        //2.解归档授权模型
         account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.filepath) as?UserAccount
        
        //3.判断是否过期
        if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending{
            return nil
        }
        
        return account
        
    }
    
    
    
    //MARK: NSCoding
    ///将对象写入到本地
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")


    }
    
    required init?(coder aDecoder: NSCoder){
       access_token = aDecoder.decodeObjectForKey("access_token") as?String
        expires_in = aDecoder.decodeObjectForKey("expires_in")  as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid")  as?String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date")  as?NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name")  as?NSString
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")  as?NSString


    }
    
    
    ///返回是否需要登陆
    class func userLogin() -> Bool{
        return UserAccount.loadAcount() != nil//判断本地用户数据是否存在
    }
    
    
    
    
}
